package guoanmaker.operator.business.scheduled;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import guoanmaker.operator.business.dao.OperatorEventDetailsDao;
import guoanmaker.operator.business.model.OperatorActivityEnlist;
import guoanmaker.operator.business.model.OperatorEventDetails;
import guoanmaker.operator.business.model.PersonalUserCoupon;
import guoanmaker.operator.business.repository.OperatorActivityEnlistRepository;
import guoanmaker.operator.business.repository.OperatorActivityPriceRepository;
import guoanmaker.operator.business.repository.OperatorCouponsRepository;
import guoanmaker.operator.business.repository.OperatorEventDetailsRepository;
import guoanmaker.operator.business.repository.PersonalUserCouponRepository;
import guoanmaker.operator.helper.common.util.sendCode;

@Configuration
@EnableScheduling
public class OperatorTask {

	private final OperatorActivityEnlistRepository operatorActivityEnlistRepository;
	private final OperatorEventDetailsRepository operatorEventDetailsRepository;
	private final PersonalUserCouponRepository personalUserCouponRepository;
	private final OperatorCouponsRepository operatorCouponsRepository;
	@PersistenceContext
	private EntityManager manager;
	@Autowired
	private OperatorActivityPriceRepository activityPriceRepository;
	

	public OperatorTask(OperatorActivityEnlistRepository operatorActivityEnlistRepository,
			OperatorEventDetailsRepository operatorEventDetailsRepository,
			PersonalUserCouponRepository personalUserCouponRepository,
			OperatorCouponsRepository operatorCouponsRepository) {
		this.operatorActivityEnlistRepository = operatorActivityEnlistRepository;
		this.operatorEventDetailsRepository = operatorEventDetailsRepository;
		this.personalUserCouponRepository = personalUserCouponRepository;
		this.operatorCouponsRepository = operatorCouponsRepository;
	}

	/**
	 * 定时器
	 */
	@Scheduled(cron = "0 */3 * * * ?") // 每隔3分执行一次
	@Transactional
	public void TimedTask() {
		Date date = new Date();
		// System.out.println("执行定时任务");
		String jpql = "select new guoanmaker.operator.business.model.OperatorActivityEnlist(oae.id,oae.inforValue,oae.userId,oae.activityId,oae.linkMan,oae.telePhone,"
				+ "oae.buyNum,oae.payMoney,oae.companyName,oae.state,oae.streamNum,oae.buildTime,oae.activityPriceId) "
				+ " from OperatorActivityEnlist  oae where  oae.streamNum is null or oae.streamNum='' or  oae.streamNum=null and (oae.state=0 or oae.state=2   )";
		Query query = manager.createQuery(jpql);
		@SuppressWarnings("unchecked")
		List<OperatorActivityEnlist> enlistlist = query.getResultList();
		manager.clear();
		if (enlistlist.size() > 0) {
			for (OperatorActivityEnlist enlist : enlistlist) {
				OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository
						.findOne(enlist.getActivityId());
				if (operatorEventDetails.getSignupEndTime() != null) {
					Long endtime = operatorEventDetails.getSignupEndTime().getTime();
					if (endtime > date.getTime()) {// 如果当前时间小于报名结束时间
						long builderTime = enlist.getBuildTime().getTime() + 7200000;// 订单交易有效时间2小时
						if (date.getTime() >= builderTime && enlist.getState() == 0) {// 超过时间段的订单
																						// 变更状态
							String id = enlist.getId();
							Integer orgState = enlist.getState();
							Integer state = 2;
							try {
								operatorActivityEnlistRepository.updateActivityEnlistState(state, orgState, id);
								if (operatorEventDetails.getIsMoney() == 1) {// 收费
									int count = activityPriceRepository.updateRemoveSellNum(enlist.getActivityPriceId(),
											enlist.getBuyNum());
									if (count == 0) {
										throw new Exception("数据修改失败");
									}
								}
								if (operatorEventDetails.getIsMoney() == 0) {// 不收费
									operatorEventDetailsRepository.updateEnrollmentRemove(enlist.getActivityId(),
											enlist.getBuyNum());
								}
							} catch (Exception e) {
								e.printStackTrace();
								System.out.println(e.getMessage());
							}
						}

					}
					if (endtime <= date.getTime() && enlist.getState() == 0) {//
						String id = enlist.getId();
						Integer orgState = enlist.getState();
						Integer state = 3;
						try {
							operatorActivityEnlistRepository.updateActivityEnlistState(state, orgState, id);
							if (operatorEventDetails.getIsMoney() == 1) {// 收费
								int count = activityPriceRepository.updateRemoveSellNum(enlist.getActivityPriceId(),
										enlist.getBuyNum());
								if (count == 0) {
									throw new Exception("数据修改失败");
								}
							}
							if (operatorEventDetails.getIsMoney() == 0) {// 不收费
								operatorEventDetailsRepository.updateEnrollmentRemove(enlist.getActivityId(),
										enlist.getBuyNum());
							}
						} catch (Exception e) {
							e.printStackTrace();
							System.out.println(e.getMessage());
						}
					}
				}
			}
		}
	}

	@Scheduled(cron = "0 */5 * * * ?") // 每隔5分执行一次
	@Transactional
	public void TimedTaskPolling() {
		Date date = new Date();
		// System.out.println("执行轮询任务");
		String jpql = "select new guoanmaker.operator.business.model.OperatorActivityEnlist(oae.id,oae.userId,oae.activityId,"
				+ "oae.state,oae.streamNum,oae.buildTime,oae.activityPriceId,oae.buyNum) "
				+ " from OperatorActivityEnlist  oae where oae.streamNum!=null  or oae.streamNum!=''  and  oae.state=0 ";
		Query query = manager.createQuery(jpql);
		@SuppressWarnings("unchecked")
		List<OperatorActivityEnlist> enlistlist = query.getResultList();
		manager.clear();
		if (enlistlist.size() > 0) {
			for (OperatorActivityEnlist enlist : enlistlist) {
				OperatorEventDetails operatorEventDetails = operatorEventDetailsRepository
						.findOne(enlist.getActivityId());
				Long endtime = operatorEventDetails.getSignupEndTime().getTime();
				if (endtime > date.getTime()) {
					long builderTime = enlist.getBuildTime().getTime() + 7200000;// 订单交易有效时间2小时
					if (date.getTime() < builderTime) {// 没有超过时间段的订单 变更状态
						String pink = enlist.getStreamNum();
						URL url;
						try {
							url = new URL("https://tpay.gack.citic/select/payorder?pingId=" + pink + "");
							HttpURLConnection conn = (HttpURLConnection) url.openConnection();
							conn.setDoInput(true);
							conn.setDoOutput(true);
							conn.setRequestMethod("POST");
							conn.setAllowUserInteraction(false);
							conn.setUseCaches(false);
							InputStream input = conn.getInputStream();
							int resLen = 0;
							byte[] res = new byte[1024];
							StringBuilder sb = new StringBuilder();
							while ((resLen = input.read(res)) != -1) {
								sb.append(new String(res, 0, resLen));
							}
							String jsonStr = sb.toString();
							if (jsonStr.equals("1") == true) {
								String id = enlist.getId();
								Integer orgState = 0;
								Integer state = 1;
								int count = operatorActivityEnlistRepository.updateActivityEnlistState(state, orgState,
										id);// 订单
								if (count == 1) {
									// 发送短信息
									try {
										sendCode.sendMessage(enlist.getTelePhone(),
												"尊敬的客户您好，您已成功报名" + operatorEventDetails.getEventTitle()
														+ "活动，感谢您的参与，谢谢！客服热线：4008518585");
									} catch (Exception e) {
										e.printStackTrace();
									}

								} // 状态 变为支付
								if (enlist.getCouponId() != null && enlist.getCouponId().equals("")==false ) {
									String ids[] = enlist.getCouponId().split(",");
									for (int numcou = 0; numcou < ids.length; numcou++) {
										PersonalUserCoupon personalUserCoupon = personalUserCouponRepository.findOne(ids[numcou]);
										personalUserCouponRepository.updateIsUsedByid(ids[numcou]);
										operatorCouponsRepository.updateBeenusedByid(personalUserCoupon.getOcId());
									}
								}
							}
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				if (endtime <= date.getTime() && enlist.getState() == 0) {//
					String id = enlist.getId();
					Integer orgState = 0;
					Integer state = 3;
					try {
						operatorActivityEnlistRepository.updateActivityEnlistState(state, orgState, id);
						if (operatorEventDetails.getIsMoney() == 1) {// 收费
							int count = activityPriceRepository.updateRemoveSellNum(enlist.getActivityPriceId(),
									enlist.getBuyNum());
							if (count == 0) {
								throw new Exception("数据修改失败");
							}
						}
						if (operatorEventDetails.getIsMoney() == 0) {// 不收费
							operatorEventDetailsRepository.updateEnrollmentRemove(enlist.getActivityId(),
									enlist.getBuyNum());
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	@Scheduled(cron = "0 */1 * * * ?")
	@Transactional
	public void TimedTasEvent() {
		Long nowTime= new Date().getTime();//获取当前时间
		String jpql = "select s from  OperatorEventDetails s where s.availability=1 and s.state <> 4";
		Query query = manager.createQuery(jpql);
		List<OperatorEventDetails> operatorEventDetails = query.getResultList();
        /* 0未发布  1活动未开始（报名结束） 2已开始  3已结束  4已删除   5报名中   6报名未开始 (已发布）   7未生效*/
		for (OperatorEventDetails eventDetails : operatorEventDetails) {
		    Integer orgstate =eventDetails.getState();
		    // 0未发布 默认 状态  7是未生效  4 是已删除
		    //报名未开始   6  报名时间 不为空     
			if(eventDetails.getSignupStartTime() !=null && eventDetails.getSignupStartTime().getTime()>nowTime && eventDetails.getReleaseTime().getTime()<= nowTime && orgstate !=6 && orgstate!=3){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),6);
			}
			//报名中  5   报名时间 不为空   
			else if(eventDetails.getSignupStartTime() !=null && eventDetails.getSignupStartTime().getTime()<=nowTime && eventDetails.getSignupEndTime().getTime()>nowTime && orgstate!= 5 && orgstate!=3){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),5);
			}
			//未开始   1 活动开始时间 不能为空    
			else if(eventDetails.getEventStartTime() !=null && eventDetails.getSignupStartTime() !=null && eventDetails.getEventStartTime().getTime() >nowTime && eventDetails.getSignupEndTime().getTime() <=nowTime  && orgstate!= 1 && orgstate!=3 ){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),1);
			}
			//未开始   1 活动开始时间 不能为空      
			else if(eventDetails.getEventStartTime() !=null   && eventDetails.getSignupStartTime() ==null && eventDetails.getEventStartTime().getTime() >nowTime && eventDetails.getReleaseTime().getTime() <=nowTime && orgstate!= 1 && orgstate!=3){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),1);
			}
			//活动开始 2   活动开始时间 不能为空  
			else if(eventDetails.getEventStartTime() !=null && eventDetails.getEventStartTime().getTime()<=nowTime && eventDetails.getEventEndTime().getTime()>nowTime && orgstate!=2 && orgstate!=3){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),2);
			}
			//活动结束 3   活动结束 时间 不能为空
			else if(eventDetails.getEventEndTime() !=null && eventDetails.getEventEndTime().getTime()< nowTime && orgstate!=3){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),3);
			}
		}
	}
	
}
